package com.sunday.fangdaifu.activity.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.squareup.picasso.Picasso;
import com.sunday.common.action.Logout;
import com.sunday.common.base.BaseFragment;
import com.sunday.common.event.EventBus;
import com.sunday.common.imageselector.MultiImageSelectorActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ImageUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.CircleImageView;
import com.sunday.common.widgets.UIAlertView;
import com.sunday.fangdaifu.R;
import com.sunday.fangdaifu.activity.common.SettingActivity;
import com.sunday.fangdaifu.activity.login.ForgetPwdActivity;
import com.sunday.fangdaifu.activity.login.LoginActivity;
import com.sunday.fangdaifu.base.MyApplication;
import com.sunday.fangdaifu.common.Api;
import com.sunday.fangdaifu.common.ApiClient;
import com.sunday.fangdaifu.common.ApiServiceImpl;
import com.sunday.fangdaifu.model.Member;
import com.sunday.fangdaifu.model.UploadImg;
import com.sunday.fangdaifu.utils.SharePerferenceUtils;

import java.io.File;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

/**
 * Created by yun_sheng on 2017/6/29.
 */

public class MyFragment extends BaseFragment implements ApiServiceImpl.HttpResponseInterface{
    @Bind(R.id.avator)
    CircleImageView avator;
    @Bind(R.id.tv_phone)
    TextView tvPhone;
    @Bind(R.id.ly_update_pwd)
    RelativeLayout lyUpdatePwd;
    @Bind(R.id.ly_setting)
    RelativeLayout lySetting;
    @Bind(R.id.btn_exit_login)
    TextView btnExitLogin;
    private Member member;

    public static MyFragment newInstance() {
        MyFragment fragment = new MyFragment();
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_my, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        init();
    }

    private void init(){
        member = (Member) SharePerferenceUtils.getIns().getOAuth();
        if (!TextUtils.isEmpty(member.getLogo())) {
            Picasso.with(mContext)
                    .load(member.getLogo())
                    .error(R.mipmap.ic_launcher)
                    .resize(130, 130)
                    .into(avator);
        }
        String phones= member.getMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
        tvPhone.setText(phones);
    }

    private final static int REQUEST_IMAGE = 0x1111;
    @OnClick({R.id.ly_update_pwd, R.id.ly_setting, R.id.btn_exit_login,R.id.avator})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.ly_update_pwd:
                intent=new Intent(mContext,ForgetPwdActivity.class);
                startActivity(intent);
                break;
            case R.id.ly_setting:
                intent=new Intent(mContext,SettingActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_exit_login:
                showLogoutDialog();
                break;
            case R.id.avator:
                intent = new Intent(mContext, MultiImageSelectorActivity.class);
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
                startActivityForResult(intent, REQUEST_IMAGE);
                break;
        }
    }

    private ArrayList<String> mSelectPath = new ArrayList<>();
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_IMAGE:
                mSelectPath.clear();
                mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                if (mSelectPath != null) {
                    String logo = ImageUtils.getCompressImagePath(mSelectPath.get(0));
                    Picasso.with(mContext)
                            .load(new File(logo))
                            .placeholder(R.drawable.logo)
                            .error(R.drawable.logo)
                            .into(avator);
                    uploadImg(logo);
                }
                break;

        }
    }

    private void uploadImg(String path){
        showLoadingDialog();
        ApiClient.getApiService().uploadSingle(path,this,new TypeToken<ResultDO<UploadImg>>(){}.getType());

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
    private void showLogoutDialog(){
        final UIAlertView delDialog = new UIAlertView(mContext, "温馨提示", "退出登录？",
                "取消", "确定");
        delDialog.show();
        delDialog.setClicklistener(new UIAlertView.ClickListenerInterface() {
                                       @Override
                                       public void doLeft() {
                                           delDialog.dismiss();
                                       }

                                       @Override
                                       public void doRight() {
                                           SharePerferenceUtils.getIns().removeKey("oAuth");
                                           EventBus.getDefault().post(new Logout());
                                           intent = new Intent(mContext,LoginActivity.class);
                                           startActivity(intent);
                                           getActivity().finish();
                                       }
                                   }
        );

    }

    @Override
    public void onResponce(String key, Object result) {
        if (isFinish) {
            return;
        }
       switch (key){
           case Api.UP_LOAD_SINGLE_IMG:
               dissMissDialog();
               ResultDO<UploadImg> resultDO= (ResultDO<UploadImg>) result;
               if (resultDO.getCode()==0){
                   String newLogo=resultDO.getResult().getUrl();
                   showLoadingDialog();
                    ApiClient.getApiService().updateLogo(member.getId(),newLogo,this,new TypeToken<ResultDO<Member>>(){}.getType());
               }
               break;
           case Api.UPDATE_LOGO:
               dissMissDialog();
               ResultDO<Member> resultDO1= (ResultDO<Member>) result;
               if (resultDO1.getCode()==0){
                   Member member=resultDO1.getResult();
                 SharePerferenceUtils.getIns().saveOAuth(member);
                   MyApplication.getInstance().setMembe(member);
               }
               break;
       }
    }

    @Override
    public void onFailure() {
        dissMissDialog();
        ToastUtils.showToast(mContext,"网络连接错误");
    }
}
